package multiThreading;

public class F extends Thread{
    private String lock1="lock1";
    private String lock2="lock2";
    public static void main(String arg[]){
        F f=new F();
        System.out.println("死锁实例：");
        new Thread(new Runnable() {
            @Override
            public void run() {
                f.getMothod1();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                f.getMothod2();
            }
        }).start();
    }
    public  void  getMothod1(){
        synchronized (lock1) {//第一个线程先锁住自己
            try {
                for (int i = 0; i < 3; i++) {
                    sleep(1000);
                    System.out.println("方法1执行了" + i + "次");
                    synchronized (lock2){}//但是在还没有出循环的时候就直接锁住第二个线程了
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public  void  getMothod2(){
        synchronized (lock2) {
            try {
                for (int i = 0; i < 3; i++) {
                    sleep(1000);
                    System.out.println("方法2执行了" + i + "次");
                    synchronized (lock1){}
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
